package com.example.boot.rtorder.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.example.boot.rtorder.dao.RtOrderDao;
import com.example.boot.rtorder.model.RtOrder;
import com.example.boot.rtorder.service.RtOrderService;
import com.example.boot.rtorder.vo.UserOrderEntity;
import com.example.boot.rtorderdetail.dao.RtOrderDetailDao;
import com.example.boot.rtorderdetail.model.RtOrderDetail;
import com.example.boot.rtshop.dao.RtShopDao;
import com.example.boot.util.JSONToObj;
import com.example.boot.util.NewUUID;
import com.example.boot.util.OrderNoCreate;

import net.sf.json.JSONArray;

@Service
public class RtOrderImpl implements RtOrderService {
	@Autowired
	private RtOrderDao rtOrderDao;
	@Autowired
	private RtOrderDetailDao rtOrderDetailDao;
	@Autowired
	private RtShopDao rtShopDao;

	@Override
	@Transactional // 该注解就是
	public boolean addOrder(String orderStr, String detailList) throws Exception {
		JSONToObj jo = new JSONToObj();
		OrderNoCreate orderNo = new OrderNoCreate();
		String orderUuid = NewUUID.UUID();
		RtOrder order = (RtOrder) jo.JsonToClass(orderStr, new RtOrder());
		String createNo = orderNo.createNo("a");
		Date createDate = new Date();
		order.setOrderStatus(0);
		order.setRtOrder(createNo);
		order.setBpmStatus(0);
		order.setCreateDate(new Date());
		order.setCreateDate(createDate);
		order.setUpdateDate(createDate);
		order.setId(orderUuid);
		rtOrderDao.insert(order);
		// JSONObject detailArray= JSONObject.fromObject("detailList");
		net.sf.json.JSONArray detailObjStr = JSONArray.fromObject(detailList);
		for (int i = 0; i < detailObjStr.size(); i++) {
			String rto = detailObjStr.get(i).toString();
			RtOrderDetail jsonToClass = (RtOrderDetail) jo.JsonToClass(rto, new RtOrderDetail());
			jsonToClass.setBpmStatus(0);
			jsonToClass.setCreateDate(createDate);
			jsonToClass.setUpdateDate(createDate);
			jsonToClass.setOrderId(orderUuid);
			jsonToClass.setId(NewUUID.UUID());
			rtOrderDetailDao.insert(jsonToClass);
		}

		return true;
	}

	@Override
	public List<UserOrderEntity> userOrder(String openId) throws Exception {
		List<RtOrder> userOrder = rtOrderDao.userOrder(openId);
		List<UserOrderEntity> list = new ArrayList<>();
		for (RtOrder rt : userOrder) {
			UserOrderEntity obj = new UserOrderEntity();
			rt.setDetailList(rtOrderDetailDao.byOrderIdFindByDetail(rt.getId()));
			obj.setOrder(rt);
			obj.setShop(rtShopDao.selectByPrimaryKey(rt.getShopId()));
			list.add(obj);
		}

		return list;
	}

}
